<?php
namespace app\api\controller;

use app\common\controller\BaseController;
use app\common\services\AttributionService;
use app\common\services\DeviceFingerprintService;
use app\common\services\AntiFraudService;
use app\common\services\InvitationFreeInstallService;
use support\Container;
use support\Request;

/**
 * 归因追踪控制器
 * 处理设备归因、参数传递、安装追踪等核心功能
 */
class AttributionController extends BaseController
{
    protected $attributionService;
    protected $deviceFingerprintService;
    protected $antiFraudService;
    protected $invitationFreeInstallService;

    public function __construct()
    {
        $this->attributionService = new AttributionService();
        $this->deviceFingerprintService = new DeviceFingerprintService();
        $this->antiFraudService = new AntiFraudService();
        $this->invitationFreeInstallService = new InvitationFreeInstallService();
    }

    /**
     * 设备信息上报接口
     * 用于收集设备信息和追踪参数
     */
    public function trackDevice()
    {
        $appkey = request()->appkey ?? '';
        $fingerprint = request()->fingerprint ?? '';
        $deviceInfo = request()->post('deviceInfo', []);
        $customParams = request()->post('customParams', []);
        $sessionId = request()->post('sessionId', '');

        // 参数验证
        if (empty($appkey) || empty($fingerprint)) {
            return json(['code' => 400, 'msg' => 'Missing required parameters']);
        }

        try {
            // 反作弊检测
            $fraudCheck = $this->antiFraudService->checkDeviceFraud($deviceInfo, $fingerprint);
            if (!$fraudCheck['allowed']) {
                return json([
                    'code' => 403, 
                    'msg' => 'Device blocked: ' . $fraudCheck['reason']
                ]);
            }

            // 生成增强设备指纹
            $enhancedFingerprint = $this->deviceFingerprintService->generateFingerprint($deviceInfo, $fingerprint);
            
            // 存储设备追踪数据
            $trackingResult = $this->attributionService->trackDevice(
                $appkey,
                $enhancedFingerprint,
                $deviceInfo,
                $customParams,
                $sessionId
            );

            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => [
                    'trackingId' => $trackingResult['tracking_id'],
                    'sessionId' => $trackingResult['session_id'],
                    'fingerprint' => $enhancedFingerprint,
                    'expireTime' => $trackingResult['expire_time'],
                    'attributionWindow' => $trackingResult['attribution_window']
                ]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => 'Internal server error',
                'error' => $this->isDebugMode() ? $e->getMessage() : null
            ]);
        }
    }

    /**
     * 获取安装参数接口
     * APP安装后获取归因参数
     */
    public function getInstallParams()
    {
        $appkey = request()->appkey ?? '';
        $fingerprint = request()->fingerprint ?? '';
        $deviceId = request()->post('deviceId', '');
        $installTime = request()->post('installTime', time());

        if (empty($appkey) || empty($fingerprint)) {
            return json(['code' => 400, 'msg' => 'Missing required parameters']);
        }

        try {
            // 执行归因算法
            $attributionResult = $this->attributionService->attributeInstall(
                $appkey,
                $fingerprint,
                $deviceId,
                $installTime
            );

            if ($attributionResult['success']) {
                return json([
                    'code' => 200,
                    'msg' => 'success',
                    'data' => [
                        'custom' => $attributionResult['custom_params'],
                        'attribution' => [
                            'channel' => $attributionResult['channel'],
                            'matchType' => $attributionResult['match_type'],
                            'confidence' => $attributionResult['confidence'],
                            'attributedAt' => $attributionResult['attributed_at']
                        ],
                        'deviceInfo' => [
                            'fingerprint' => $fingerprint,
                            'deviceId' => $deviceId
                        ]
                    ]
                ]);
            } else {
                return json([
                    'code' => 404,
                    'msg' => 'No attribution data found',
                    'data' => [
                        'custom' => [],
                        'attribution' => null
                    ]
                ]);
            }

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => 'Internal server error',
                'error' => $this->isDebugMode() ? $e->getMessage() : null
            ]);
        }
    }

    /**
     * 事件上报接口
     * 用于追踪用户行为事件
     */
    public function trackEvent()
    {
        $appkey = request()->appkey ?? '';
        $fingerprint = request()->fingerprint ?? '';
        $eventType = request()->post('eventType', '');
        $eventData = request()->post('eventData', []);
        $sessionId = request()->post('sessionId', '');

        if (empty($appkey) || empty($fingerprint) || empty($eventType)) {
            return json(['code' => 400, 'msg' => 'Missing required parameters']);
        }

        try {
            // 验证事件类型
            $validEvents = ['install', 'open', 'register', 'purchase', 'custom'];
            if (!in_array($eventType, $validEvents)) {
                return json(['code' => 400, 'msg' => 'Invalid event type']);
            }

            // 存储事件数据
            $eventResult = $this->attributionService->trackEvent(
                $appkey,
                $fingerprint,
                $eventType,
                $eventData,
                $sessionId
            );

            return json([
                'code' => 200,
                'msg' => 'Event tracked successfully',
                'data' => [
                    'eventId' => $eventResult['event_id'],
                    'processed' => $eventResult['processed'],
                    'timestamp' => $eventResult['timestamp']
                ]
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => 'Internal server error',
                'error' => $this->isDebugMode() ? $e->getMessage() : null
            ]);
        }
    }

    /**
     * 实时统计接口
     * 获取应用的实时统计数据
     */
    public function getRealtimeStats()
    {
        $appkey = request()->appkey ?? '';
        $timeRange = request()->post('timeRange', '24h');

        if (empty($appkey)) {
            return json(['code' => 400, 'msg' => 'Missing appkey parameter']);
        }

        try {
            $stats = $this->attributionService->getRealtimeStats($appkey, $timeRange);
            
            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $stats
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => 'Internal server error',
                'error' => $this->isDebugMode() ? $e->getMessage() : null
            ]);
        }
    }

    /**
     * 渠道分析接口
     * 获取渠道转化分析数据
     */
    public function getChannelAnalytics()
    {
        $appkey = request()->appkey ?? '';
        $startDate = request()->post('startDate', date('Y-m-d', strtotime('-7 days')));
        $endDate = request()->post('endDate', date('Y-m-d'));
        $channels = request()->post('channels', []);

        if (empty($appkey)) {
            return json(['code' => 400, 'msg' => 'Missing appkey parameter']);
        }

        try {
            $analytics = $this->attributionService->getChannelAnalytics(
                $appkey,
                $startDate,
                $endDate,
                $channels
            );

            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $analytics
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => 'Internal server error',
                'error' => $this->isDebugMode() ? $e->getMessage() : null
            ]);
        }
    }

    /**
     * 免邀请安装处理接口
     * 处理APP安装时的免邀请码归因逻辑
     */
    public function processInvitationFreeInstall()
    {
        $appkey = request()->appkey ?? '';
        $deviceInfo = request()->post('deviceInfo', []);
        $installParams = request()->post('installParams', []);
        $deviceId = request()->post('deviceId', '');
        $installTime = request()->post('installTime', time());

        // 参数验证
        if (empty($appkey) || empty($deviceInfo)) {
            return json(['code' => 400, 'msg' => 'Missing required parameters']);
        }

        try {
            // 执行免邀请安装处理
            $result = $this->invitationFreeInstallService->processInvitationFreeInstall(
                $appkey,
                $deviceInfo,
                $installParams
            );

            if ($result['success']) {
                return json([
                    'code' => 200,
                    'msg' => 'Installation processed successfully',
                    'data' => [
                        'install_id' => $result['data']['install_id'],
                        'channel' => $result['data']['channel'],
                        'inviter_info' => $result['data']['inviter_info'],
                        'custom_params' => $result['data']['custom_params'],
                        'attribution_result' => $result['data']['attribution_result'],
                        'device_fingerprint' => $result['data']['device_fingerprint']
                    ]
                ]);
            } else {
                return json([
                    'code' => 404,
                    'msg' => $result['reason'] ?? 'Installation attribution failed',
                    'data' => [
                        'suggestion' => $result['suggestion'] ?? 'Please ensure the device has visited the promotion link before installation',
                        'channel' => 'organic',
                        'custom_params' => []
                    ]
                ]);
            }

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => 'Internal server error',
                'error' => $this->isDebugMode() ? $e->getMessage() : null
            ]);
        }
    }

    /**
     * 获取免邀请安装参数
     * APP启动时获取归因参数和邀请信息
     */
    public function getInvitationFreeInstallParams()
    {
        $appkey = request()->appkey ?? '';
        $deviceId = request()->post('deviceId', '');
        $deviceFingerprint = request()->post('deviceFingerprint', '');

        // 参数验证
        if (empty($appkey) || (empty($deviceId) && empty($deviceFingerprint))) {
            return json(['code' => 400, 'msg' => 'Missing required parameters']);
        }

        try {
            // 获取安装参数
            $result = $this->invitationFreeInstallService->getInstallParams(
                $appkey,
                $deviceId,
                $deviceFingerprint
            );

            if ($result['success']) {
                return json([
                    'code' => 200,
                    'msg' => 'Install parameters retrieved successfully',
                    'data' => $result['data']
                ]);
            } else {
                return json([
                    'code' => 404,
                    'msg' => $result['reason'] ?? 'No installation parameters found',
                    'data' => [
                        'channel' => 'organic',
                        'custom_params' => [],
                        'inviter_info' => null
                    ]
                ]);
            }

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => 'Internal server error',
                'error' => $this->isDebugMode() ? $e->getMessage() : null
            ]);
        }
    }

    /**
     * 验证归因结果
     * 用于验证归因准确性和调试
     */
    public function validateAttribution()
    {
        $appkey = request()->appkey ?? '';
        $fingerprint = request()->fingerprint ?? '';
        $deviceId = request()->post('deviceId', '');

        if (empty($appkey) || empty($fingerprint)) {
            return json(['code' => 400, 'msg' => 'Missing required parameters']);
        }

        try {
            $validation = $this->attributionService->validateAttribution(
                $appkey,
                $fingerprint,
                $deviceId
            );

            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $validation
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => 'Internal server error',
                'error' => $this->isDebugMode() ? $e->getMessage() : null
            ]);
        }
    }

    /**
     * 检查是否为调试模式
     */
    private function isDebugMode()
    {
        return config('app.debug', false);
    }
}